-- pass_instance
-- Created by chengb Jul/10/2015
-- 成就：通关副本（如：怪物洞窟）

-- 内部函数声明
local whenPassInstance;

-- 注册玩家通关副本的回调
EventMgr.register("achievements/pass_instance", event.INSTANCE_DISAPPER, function(args)
    whenPassInstance(args);
end);

-- 注册玩家通关副本的回调
whenPassInstance = function(args)
    local instanceId   = args.id;
    local instanceInfo = DungeonInstanceM.getInstanceInfo(instanceId);
    local intanceType  = instanceInfo.type;

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("pass_instance");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        -- 判断是否是需求副本
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["instance_type"]) == 'number' and 
                ruleArg["instance_type"] ~= intanceType then
                return false;
            end
            
            if type(ruleArg["instance_id"]) == 'number' and 
                ruleArg["instance_id"] ~= instanceId then
                return false;
            end
            
            if type(ruleArg["instance_id"]) == 'table' and 
                table.indexOf(ruleArg["instance_id"], instanceId) == -1 then
                return false;
            end
            
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {

};